<?php

namespace app\admin\validate;

use think\Validate;
use think\Db;

/**
 * auth验证器
 */
class Feedback extends Validate
{

    protected $rule = [
        'captcha|验证码' => 'require|captcha',
        'title' => 'max:25',
        'content' => 'require|max:500',
        'feedback_id' => 'require|integer',
    ];

    protected $message = [
        'content.require' => '反馈内容必填',
        'content.max' => '反馈内容不得超过500字',
        'title.max' => '标题不得超过25个字',
    ];

    protected $scene = [
        'add' => ['captcha','title','content',],
        'user_reply' => ['captcha','content','feedback_id'],
        'admin_reply' => ['content','feedback_id']
        
    ];

    // 自定义notNumber规则，非纯数字通过
    protected function notNumber($value, $rule)
    {
        return !is_numeric($value);
    }

    // 不能有空格
    protected function nospace($value, $rule)
    {
        $arr = explode(" ", $value);
        if (count($arr) >= 2) {
            return false;
        }
        return true;

    }

    //不允许特殊字符
    protected function specialchar($value, $rule)
    {
        if (preg_match("/[\'.,:;*?~`!@#$%^&+=)(<{}]|\]|\[|\/|\\\|\"|\|/", $value)) {
            return false;
        }
        return true;

    }

    // 验证用户名 允许5-12字符或2-12汉字
    protected function checkName($value, $rule)
    {
        if (strlen($value) < 5 || mb_strlen($value) > 12) {
            return false;
        }
        return true;
    }

    // 自定义exists规则，与unique用法一致，返回结果相反
    protected function exists($value, $rule, $data, $field)
    {
        if (is_string($rule)) {
            $rule = explode(',', $rule);
        }
        $db = Db::name($rule[0]);
        $key = isset($rule[1]) ? $rule[1] : $field;

        if (strpos($key, '^')) {
            // 支持多个字段验证
            $fields = explode('^', $key);
            foreach ($fields as $key) {
                $map[$key] = $data[$key];
            }
        } elseif (strpos($key, '=')) {
            parse_str($key, $map);
        } else {
            $map[$key] = $data[$field];
        }

        $pk = strval(isset($rule[3]) ? $rule[3] : $db->getPk());
        if (isset($rule[2])) {
            $map[$pk] = ['neq', $rule[2]];
        } elseif (isset($data[$pk])) {
            $map[$pk] = ['neq', $data[$pk]];
        }

        if ($db->where($map)->field($pk)->find()) {
            return true;
        }
        return false;
    }
}
